'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 用户相关
 * @author sundbcn@gmail.com (sun debing)
 */

var pomelo = require('pomelo');
var async = require('async');
var _ = require('lodash');
var Code = require('../../../consts/code');
var roleModel = require('../../../models/roleModel');
var channelUtil = require('../../../util/channelUtil');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 在线用户列表
 */
Handler.prototype.getOnlineList = function (msg, session, next) {
    var channel_id = msg.query.channel_id;
    pomelo.app.get('globalChannelService').getMembersByChannelName(
        'connector',
        channelUtil.getGlobalChannelName(),
        function (err, members) {
            _getMembersInfo(members, channel_id, function (err, online_list) {
                return next(null, {
                    code: Code.OK,
                    result: {
                        online_list: online_list
                    }
                });
            });
        }
    );
};

/**
 * 获取用户的信息
 * @param  {[type]} members [description]
 * @return {[type]}         [description]
 */
var _getMembersInfo = function (members, channel_id, callback) {
    var online_list = [];
    var count = 0;
    async.whilst(
        function () {
            return count < _.size(members);
        },
        function (cb) {
            var uid = members[count];
            roleModel.getByRoleId(+uid, function (err, role_model) {
                if (channel_id === '381190366' || role_model.channel_id === channel_id) {
                    online_list.push({
                        role_id: role_model.getRoleId(),
                        name: role_model.getName(),
                        gold: role_model.getGold(),
                        diamond: role_model.getDiamond(),
                        food: role_model.getFood(),
                        channel_id: role_model.channel_id
                    });
                }
                cb();
            });
            count++;
        },
        function (err) {
            callback(null, online_list);
        }
    );
};
